<template>
  <div class="campus-manager">
    <!-- 管理器头部 -->
    <div class="manager-header">
      <div class="manager-info">
        <h4>校区公告管理</h4>
        <p>选择要在小程序中显示的校区公告</p>
      </div>
      <div class="manager-actions">
        <el-button @click="refreshList" size="small" icon="el-icon-refresh">刷新</el-button>
        <el-button @click="handleAdd" type="primary" size="small" icon="el-icon-plus">新增</el-button>
      </div>
    </div>

    <!-- 校区公告网格 -->
    <div class="campus-grid">
      <div 
        v-for="campus in campusAds" 
        :key="campus.id"
        :class="['campus-card', { 'selected': selectedCampus.includes(campus.id) }]"
        @click="toggleSelect(campus)"
      >
        <!-- 选择指示器 -->
        <div class="select-indicator">
          <i class="el-icon-check"></i>
        </div>

        <!-- 公告信息 -->
        <div class="campus-info">
          <h4>{{ campus.title }}</h4>
          <p class="campus-tag">{{ campus.tag || '通用公告' }}</p>
          <p class="campus-time">发布时间：{{ formatDate(campus.publishTime) }}</p>
          <div class="campus-status">
            <el-tag :type="campus.status === 1 ? 'success' : 'info'" size="mini">
              {{ campus.status === 1 ? '已发布' : '草稿' }}
            </el-tag>
          </div>
        </div>

        <!-- 悬停操作 -->
        <div class="campus-overlay">
          <el-button 
            type="primary" 
            size="mini" 
            icon="el-icon-edit"
            @click.stop="handleEdit(campus)"
          >
            编辑
          </el-button>
        </div>
      </div>
    </div>

    <!-- 空状态 -->
    <div v-if="campusAds.length === 0" class="empty-state">
      <i class="el-icon-document-add"></i>
      <p>暂无校区公告</p>
      <el-button @click="handleAdd" type="primary" size="small">创建第一个公告</el-button>
    </div>

    <!-- 管理器底部 -->
    <div class="manager-footer">
      <div class="selected-info">
        已选择 {{ selectedCampus.length }} 个公告
      </div>
      <div class="actions">
        <el-button @click="handleCancel">取消</el-button>
        <el-button @click="handleConfirm" type="primary">确定</el-button>
      </div>
    </div>

    <!-- 新增/编辑公告弹窗 -->
    <el-dialog :title="editMode === 'add' ? '新增校区公告' : '编辑校区公告'" :visible.sync="editDialogVisible" width="600px">
      <el-form ref="campusForm" :model="campusForm" :rules="formRules" label-width="80px">
        <el-form-item label="公告标题" prop="title">
          <el-input v-model="campusForm.title" placeholder="请输入公告标题" />
        </el-form-item>
        <el-form-item label="公告内容" prop="content">
          <el-input 
            type="textarea" 
            v-model="campusForm.content" 
            placeholder="请输入公告内容"
            :rows="4"
          />
        </el-form-item>
        <el-form-item label="分类标签" prop="tag">
          <el-select v-model="campusForm.tag" placeholder="选择分类标签" style="width: 100%">
            <el-option label="重要公告" value="重要公告" />
            <el-option label="活动通知" value="活动通知" />
            <el-option label="课程安排" value="课程安排" />
            <el-option label="放假通知" value="放假通知" />
            <el-option label="通用公告" value="通用公告" />
          </el-select>
        </el-form-item>
        <el-form-item label="公告类型" prop="type">
          <el-select v-model="campusForm.type" placeholder="选择公告类型" style="width: 100%">
            <el-option label="普通公告" value="normal" />
            <el-option label="重要公告" value="important" />
            <el-option label="紧急公告" value="urgent" />
          </el-select>
        </el-form-item>
        <el-form-item label="发布时间" prop="publishTime">
          <el-date-picker
            v-model="campusForm.publishTime"
            type="datetime"
            placeholder="选择发布时间"
            style="width: 100%"
            value-format="yyyy-MM-dd HH:mm:ss"
          />
        </el-form-item>
        <el-form-item label="所属校区" prop="campusId" v-if="isAdmin">
          <el-select v-model="campusForm.campusId" placeholder="请选择校区" style="width: 100%">
            <el-option
              v-for="campus in campusList"
              :key="campus.campusId || campus.id"
              :label="campus.campusName || campus.name"
              :value="campus.campusId || campus.id"
            />
          </el-select>
        </el-form-item>
        <el-form-item label="所属校区" v-else>
          <el-input :value="getCurrentCampusName()" disabled />
        </el-form-item>
        <el-form-item label="状态" prop="status">
          <el-radio-group v-model="campusForm.status">
            <el-radio :label="1">发布</el-radio>
            <el-radio :label="0">草稿</el-radio>
          </el-radio-group>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="editDialogVisible = false">取 消</el-button>
        <el-button type="primary" @click="handleSave">确 定</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import { listCampus, getCampus, delCampus, addCampus, updateCampus } from "@/api/home/campus/campus"

export default {
  name: 'CampusManager',
  props: {
    selected: {
      type: Array,
      default: () => []
    },
    currentCampusId: {
      type: Number,
      default: null
    },
    isAdmin: {
      type: Boolean,
      default: false
    },
    campusList: {
      type: Array,
      default: () => []
    }
  },
  data() {
    return {
      campusAds: [],
      selectedCampus: [],
      editDialogVisible: false,
      editMode: 'add', // 'add' 或 'edit'
      campusForm: {
        id: null,
        title: '',
        content: '',
        tag: '',
        type: 'normal',
        publishTime: '',
        status: 1,
        campusId: null
      },
      formRules: {
        title: [
          { required: true, message: '请输入公告标题', trigger: 'blur' }
        ],
        content: [
          { required: true, message: '请输入公告内容', trigger: 'blur' }
        ],
        tag: [
          { required: true, message: '请选择分类标签', trigger: 'change' }
        ],
        type: [
          { required: true, message: '请选择公告类型', trigger: 'change' }
        ],
        publishTime: [
          { required: true, message: '请选择发布时间', trigger: 'change' }
        ]
      }
    }
  },
  mounted() {
    this.loadCampusAds()
    // 初始化已选择的公告
    this.initializeSelected()
  },
  watch: {
    selected: {
      handler(newVal) {
        this.initializeSelected()
      },
      immediate: true
    }
  },
  methods: {
    // 初始化已选择项
    initializeSelected() {
      if (this.selected && this.selected.length > 0) {
        // 如果传入的是公告对象数组，提取ID
        this.selectedCampus = this.selected.map(item =>
          typeof item === 'object' ? item.id : item
        )
      } else {
        this.selectedCampus = []
      }
    },

    // 加载校区公告列表
    async loadCampusAds() {
      try {
        console.log('开始加载校区公告列表...')
        const query = { pageSize: 100 } // 加载更多数据
        
        // 如果不是超级管理员，添加校区筛选
        if (!this.isAdmin && this.currentCampusId) {
          query.campusId = this.currentCampusId
        }
        
        const response = await listCampus(query)
        console.log('API响应:', response)
        
        if (response && response.rows) {
          this.campusAds = response.rows
          console.log('成功加载校区公告:', this.campusAds.length, '条')
        } else {
          console.warn('API响应格式异常:', response)
          this.campusAds = []
          this.$message.warning('暂无校区公告数据')
        }
      } catch (error) {
        console.error('加载校区公告列表失败:', error)
        this.$message.error('加载校区公告列表失败: ' + error.message)
        // 使用模拟数据用于测试
        this.campusAds = [
          {
            id: 1,
            title: '测试公告1',
            content: '这是一条测试公告内容',
            tag: '重要公告',
            type: 'important',
            publishTime: new Date().toISOString(),
            status: 1
          },
          {
            id: 2,
            title: '测试公告2',
            content: '这是另一条测试公告内容',
            tag: '活动通知',
            type: 'normal',
            publishTime: new Date().toISOString(),
            status: 1
          }
        ]
        console.log('使用模拟数据:', this.campusAds)
      }
    },

    // 切换选择状态
    toggleSelect(campus) {
      const index = this.selectedCampus.indexOf(campus.id)
      if (index > -1) {
        this.selectedCampus.splice(index, 1)
      } else {
        this.selectedCampus.push(campus.id)
      }
    },

    // 新增公告
    handleAdd() {
      this.editMode = 'add'
      this.resetForm()
      this.editDialogVisible = true
    },

    // 编辑公告
    handleEdit(campus) {
      this.editMode = 'edit'
      this.campusForm = { ...campus }
      this.editDialogVisible = true
    },

    // 保存公告
    async handleSave() {
      this.$refs.campusForm.validate(async (valid) => {
        if (valid) {
          try {
            if (this.editMode === 'add') {
              await addCampus(this.campusForm)
              this.$message.success('新增成功')
            } else {
              await updateCampus(this.campusForm)
              this.$message.success('更新成功')
            }

            this.editDialogVisible = false
            this.loadCampusAds()
          } catch (error) {
            this.$message.error('保存失败')
          }
        }
      })
    },

    // 重置表单
    resetForm() {
      this.campusForm = {
        id: null,
        title: '',
        content: '',
        tag: '',
        type: 'normal',
        publishTime: '',
        status: 1,
        campusId: this.isAdmin ? null : this.currentCampusId
      }
    },

    // 获取当前校区名称
    getCurrentCampusName() {
      if (!this.currentCampusId) {
        return '超级管理员'
      }
      const campus = this.campusList.find(c => 
        (c.campusId || c.id) === this.currentCampusId
      )
      return campus ? (campus.campusName || campus.name) : '未知校区'
    },

    // 格式化日期
    formatDate(date) {
      if (!date) return '未设置'
      try {
        const d = new Date(date)
        return d.toLocaleString('zh-CN', {
          year: 'numeric',
          month: '2-digit',
          day: '2-digit',
          hour: '2-digit',
          minute: '2-digit'
        })
      } catch (error) {
        console.warn('日期格式化失败:', date, error)
        return '时间格式错误'
      }
    },

    // 刷新列表
    refreshList() {
      this.loadCampusAds()
    },

    // 取消选择
    handleCancel() {
      this.$emit('close')
    },

    // 确认选择
    handleConfirm() {
      const selectedCampusData = this.campusAds.filter(campus =>
        this.selectedCampus.includes(campus.id)
      )
      this.$emit('select', selectedCampusData)
    }
  }
}
</script>

<style scoped>
.campus-manager {
  height: 500px;
  display: flex;
  flex-direction: column;
}

.manager-header {
  display: flex;
  justify-content: space-between;
  align-items: flex-start;
  margin-bottom: 20px;
}

.manager-info h4 {
  margin: 0 0 4px 0;
  color: #2c3e50;
  font-size: 16px;
}

.manager-info p {
  margin: 0;
  color: #666;
  font-size: 14px;
}

.manager-actions {
  display: flex;
  gap: 8px;
}

.campus-grid {
  flex: 1;
  display: grid;
  grid-template-columns: repeat(auto-fill, minmax(280px, 1fr));
  gap: 15px;
  overflow-y: auto;
  padding: 10px 0;
}

.campus-card {
  position: relative;
  border: 2px solid #e0e0e0;
  border-radius: 8px;
  padding: 20px;
  cursor: pointer;
  transition: all 0.3s;
  background: #fff;
}

.campus-card:hover {
  border-color: #1976d2;
  box-shadow: 0 4px 12px rgba(25, 118, 210, 0.15);
}

.campus-card.selected {
  border-color: #1976d2;
  background-color: #e3f2fd;
}

.campus-info h4 {
  margin: 0 0 8px 0;
  font-size: 16px;
  color: #333;
  overflow: hidden;
  text-overflow: ellipsis;
  white-space: nowrap;
}

.campus-tag {
  margin: 0 0 8px 0;
  font-size: 12px;
  color: #409eff;
  font-weight: 500;
}

.campus-time {
  margin: 0 0 12px 0;
  font-size: 12px;
  color: #999;
}

.campus-status {
  display: flex;
  justify-content: flex-end;
}

.campus-overlay {
  position: absolute;
  top: 0;
  left: 0;
  right: 0;
  bottom: 0;
  background: rgba(0, 0, 0, 0.5);
  display: flex;
  align-items: center;
  justify-content: center;
  opacity: 0;
  transition: opacity 0.3s;
}

.campus-card:hover .campus-overlay {
  opacity: 1;
}

.select-indicator {
  position: absolute;
  top: 10px;
  right: 10px;
  width: 24px;
  height: 24px;
  border-radius: 50%;
  background: #1976d2;
  color: white;
  display: flex;
  align-items: center;
  justify-content: center;
  opacity: 0;
  transition: opacity 0.3s;
}

.campus-card.selected .select-indicator {
  opacity: 1;
}

.empty-state {
  flex: 1;
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
  color: #999;
}

.empty-state i {
  font-size: 64px;
  margin-bottom: 16px;
  color: #ddd;
}

.empty-state p {
  margin: 0 0 16px 0;
  font-size: 16px;
}

.manager-footer {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-top: 20px;
  padding-top: 15px;
  border-top: 1px solid #e0e0e0;
}

.selected-info {
  color: #666;
  font-size: 14px;
}

.actions {
  display: flex;
  gap: 10px;
}
</style> 